<template>
    <el-card class="review-form-card">
        <el-form
            ref="reviewForm"
            :model="form"
            :rules="rules"
            label-width="80px"
        >
            <!-- 隐藏字段 - 用户ID和订单详情ID -->
            <el-form-item prop="userId" hidden>
                <el-input v-model="form.userId"></el-input>
            </el-form-item>

            <el-form-item prop="orderItemId" hidden>
                <el-input v-model="form.orderItemId"></el-input>
            </el-form-item>

            <!-- 评分 -->
            <el-form-item label="评分" prop="score">
                <el-rate
                    v-model="form.score"
                    :max="5"
                    :colors="['#F7BA1E', '#F7BA1E', '#F7BA1E']"
                    void-color="#C0C4CC"
                    allow-half
                    placeholder="请评分"
                ></el-rate>
            </el-form-item>

            <!-- 评价内容 -->
            <el-form-item label="评价" prop="content">
                <el-input
                    type="textarea"
                    v-model="form.content"
                    :rows="4"
                    placeholder="请输入您的评价..."
                ></el-input>
                <div class="text-right text-gray-500 text-sm mt-1">
                    {{ form.content.length }}/500
                </div>
            </el-form-item>

            <!-- 上传图片 -->
            <el-form-item label="图片">
                <el-upload
                    :action="uploadUrl"
                    :headers="uploadHeaders"
                    :on-success="handleUploadSuccess"
                    :on-error="handleUploadError"
                    :file-list="fileList"
                    list-type="picture-card"
                    :limit="3"
                    :on-exceed="handleExceed"
                >
                    <i class="el-icon-plus"></i>
                    <template #tip>
                        <div class="el-upload__tip text-sm">
                            最多上传3张图片，支持JPG、PNG格式
                        </div>
                    </template>
                </el-upload>
            </el-form-item>

            <!-- 提交按钮 -->
            <el-form-item>
                <el-button
                    type="primary"
                    @click="submitForm"
                    :loading="loading"
                >
                    <template #default>
                        <i class="el-icon-loading" v-if="loading"></i>
                        <span v-else>提交评价</span>
                    </template>
                </el-button>
                <el-button
                    type="text"
                    @click="resetForm"
                    class="ml-2"
                >
                    重置
                </el-button>
            </el-form-item>
        </el-form>
    </el-card>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElNotification } from 'element-plus';
import { useRoute } from 'vue-router';
import axios from 'axios';
import { AuthService } from '@/service/auth.ts'
const authService = new AuthService();
const userId = authService.getUserId();


// 路由信息
const route = useRoute();

// 图片上传配置
const uploadUrl = '/api/upload/image'; // 图片上传接口地址
const uploadHeaders = {
    'Authorization': `Bearer ${localStorage.getItem('token')}` // 携带认证token
};

// 表单数据 - 设置默认值为1
const form = reactive({
    userId: userId.value,            // 用户ID，默认值1
    orderItemId: route.params.orderItemId,       // 订单详情ID，默认值1
    score: null,          // 评分
    content: '',          // 评价内容
    img: []               // 图片URL数组，多个图片用逗号分隔
});

// 表单引用
const reviewForm = ref(null);

// 上传文件列表
const fileList = ref([]);

// 加载状态
const loading = ref(false);

// 验证规则
const rules = {
    userId: [
        { required: true, message: '用户信息错误', trigger: 'change' }
    ],
    orderItemId: [
        { required: true, message: '订单信息错误', trigger: 'change' }
    ],
    score: [
        { required: true, message: '请给出评分', trigger: 'change' }
    ],
    content: [
        { required: true, message: '请输入评价内容', trigger: 'blur' },
        { min: 5, message: '评价内容至少5个字', trigger: 'blur' },
        { max: 500, message: '评价内容不能超过500字', trigger: 'input' }
    ]
};

// 初始化 - 保持默认值1，不再从路由和本地存储获取
onMounted(() => {
    // 保持默认值1，注释掉从路由和本地存储获取的逻辑
    // form.orderItemId = route.params.orderItemId || 1;
    // const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{"id":1}');
    // form.userId = userInfo.id || 1;
});

// 处理文件上传成功
const handleUploadSuccess = (response, file, fileList) => {
    if (response.success) {
        // 将上传成功的图片URL添加到img数组
        form.img.push(response.data.url);
        ElMessage.success('图片上传成功');
    } else {
        ElMessage.error('图片上传失败: ' + (response.message || '未知错误'));
    }
};

// 处理文件上传失败
const handleUploadError = (error) => {
    console.error('上传失败', error);
    ElMessage.error('图片上传失败，请重试');
};

// 处理文件超出限制
const handleExceed = (files, fileList) => {
    ElMessage.warning(`最多只能上传3张图片`);
};

// 提交表单
const submitForm = async () => {
    reviewForm.value.validate(async (valid) => {
        if (valid) {
            loading.value = true;
            try {
                // 处理图片URL格式，转为逗号分隔的字符串
                const submitData = {
                    ...form,
                    img: form.img.join(',') // 后端可能期望图片URL用逗号分隔
                };

                // 调用API提交评价
                const response = await axios.post(
                    '/api/shop/review/add',
                    submitData,
                    {
                        headers: {
                            'Content-Type': 'application/json',
                            'Authorization': `Bearer ${localStorage.getItem('token')}`
                        }
                    }
                );

                // 处理后端响应
                if (response.data.includes('成功')) {
                    ElNotification({
                        title: '成功',
                        message: '评价提交成功，感谢您的反馈',
                        type: 'success',
                        duration: 3000
                    });
                    resetForm();
                } else {
                    ElMessage.error(response.data);
                }
            } catch (error) {
                console.error('提交评价失败', error);
                ElMessage.error('网络错误，提交失败，请重试');
            } finally {
                loading.value = false;
            }
        }
    });
};

// 重置表单
const resetForm = () => {
    reviewForm.value.resetFields();
    fileList.value = [];
    form.img = [];
    // 重置后保持默认的用户ID和订单ID
    form.userId = userId.value;
    form.orderItemId = route.params.orderItemId;
};

// 允许从外部设置订单ID
const setOrderItemId = (id) => {
    form.orderItemId = id;
};

// 暴露方法供父组件使用
defineExpose({ setOrderItemId });
</script>

<style scoped>
.review-form-card {
    max-width: 600px;
    margin: 20px auto;
    padding: 20px;
}
</style>
